from django.shortcuts import render,redirect
from django.http import HttpResponse
from common.models import Types
from django.core.urlresolvers import reverse
from datetime import datetime
from django.core.paginator import Paginator
#浏览
def index(request,pindex=1):
	if pindex == '' or int(pindex)<=0:
		pindex="1"
	pindex=int(pindex)
	#获取Types信息
	#_list=Types.objects.all()
	#根据层级关系进行排序
	_list=Types.objects.extra(select={'_has':'concat(path,id)'}).order_by('_has')
	pageData=Paginator(_list,6)
	list=pageData.page(pindex)
	plist=pageData.page_range
	context={'typeList':list,'plist':plist,'pageCount':pageData.num_pages,'pindex':pindex}
	return render(request,'myadmin/type/index.html',context)

#添加页面
def add(request,tid):
	#获取父类级别信息
	if tid == '0':
		context={'pid':'0','path':'0,','name':'根目录'}
	else:
		ob=Types.objects.get(id = tid)
		context={'pid':ob.id,'path':ob.path+str(ob.id)+',','name':ob.name}
	return render(request,'myadmin/type/add.html',context)

#添加操作
def insert(request):
	try:
		ob = Types()
		ob.name = request.POST['name']
		ob.pid = request.POST['pid']
		ob.path = request.POST['path']
		ob.save()
		context = {"info":"添加成功！"}	
		pindex =1
		#成功后转发至列表页面
		return redirect(reverse('myadmin_type_index',args=(pindex,)))
		#return render(request,'myadmin/info.html',content)	
	except Exception as e:
		content={'info':'添加失败：：'+str(e)}
		return render(request,'myadmin/info.html',content)

#删除
def delete(request,tid):
	try:
		childObj=Types.objects.filter(path__contains=str(tid))
		if childObj.count()>0:
			content={'info':'当前商品分类已于'+str(childObj.count())+'个类别关联，无法删除!!'}
			return render(request,'myadmin/info.html',content)
		else:
			userObj=Types.objects.get(id=tid)
			userObj.delete()		
			pindex =1
			return redirect(reverse('myadmin_type_index',args=(pindex,)))
	except Exception as e:
		content={'info':'删除失败：：'+str(e)}
		return render(request,'myadmin/info.html',content)

#编辑页面
def edit(request,tid):
	try:
		userObj=Types.objects.get(id=tid)
		content={"type":userObj}
		return render(request,'myadmin/type/edit.html',content)
	except Exception as e:
		content={'info':'查询用户详情失败：：'+str(e)}
		return render(request,'myadmin/info.html',content)


#编辑更改操作
def update(request,tid):
	try:
		ob = Types.objects.get(id=tid)
		ob.name = request.POST['name']
		ob.save()
		pindex =1
		#成功后转发至列表页面
		return redirect(reverse('myadmin_type_index',args=(pindex,)))
	except Exception as e:
		content={'info':'更改信息失败：：'+str(e)}
		return render(request,'myadmin/info.html',content)

